import csv

import numpy as np
import pandas as pd

def fix():
    # feature_columns = list(range(1, 14))
    df = pd.read_csv('../data/Water.csv')

    # 遍历每个列并替换0值
    for col in df.columns:
        # 找到所有值为0的索引
        zero_indexes = df.index[df[col] == 0].tolist()

        # 遍历所有值为0的索引
        for zero_index in zero_indexes:
            # 找到前后非零值的索引
            prev_index = zero_index - 1
            while prev_index in zero_indexes:
                prev_index -= 1

            next_index = zero_index + 1
            while next_index in zero_indexes:
                next_index += 1

            # 计算前后非零值的平均值并替换0值
            prev_val = df.iloc[prev_index][col] if prev_index >= 0 else np.nan
            next_val = df.iloc[next_index][col] if next_index < df.shape[0] else np.nan
            mean_val = np.nanmean([prev_val, next_val])
            df.iloc[zero_index, df.columns.get_loc(col)] = mean_val

    # 将修改后的数据保存为csv文件
    df.to_csv('../data/Fix-Water.csv', index=False)

#将CSV转换成多维度状态
# 例子：
#	WateId	MeasDT
# 1	1	2016/1/1 0:00
# 2	2	2016/1/1 0:00
# 3	3	2016/1/1 0:00
# 4	4	2016/1/1 0:00   =》多维度
# 5	5	2016/1/1 0:00
# 6	6	2016/1/1 0:00
# 7	7	2016/1/1 0:00
# 8	8	2016/1/1 0:00
# 9	11	2016/1/1 0:00
def CSV_data(path):
    data = pd.read_csv(path, encoding='UTF-8',usecols=[1,2,3,4])
    # 删除全为空值的行或列
    data = data.dropna()

    datalist = pd.DataFrame(columns=['date',"WaterID-1", "WaterID-2","WaterID-3","WaterID-4"
                                  , "WaterID-5","WaterID-6", "WaterID-7"
                                  ,"WaterID-8","WaterID-11","Flow-1",
                               "Flow-4","Flow-7","Flow-11"
                               ])

    # # datalist = []
    for index in range(int(len(data) / 9)):
        if data.loc[index * 9]["MeasDT"] != data.loc[index * 9 + 8]["MeasDT"]:
            raise Exception("时间周期错误！")
        list = data[index * 9:index * 9 + 1]["MeasDT"]
        list = list.append(data[index * 9:index * 9 + 9]["Level"])
        list = pd.concat([list, data[index * 9:index * 9 + 9:3]["Flow"],data[index * 9+8:index * 9 + 9]["Flow"]])
        list = list.reset_index(drop=True)

        list = {'date': list[0], "WaterID-1": list[1], "WaterID-2": list[2], "WaterID-3": list[3]
            , "WaterID-4": list[4], "WaterID-5": list[5], "WaterID-6": list[6]
            , "WaterID-7": list[7], "WaterID-8": list[8], "WaterID-11": list[9]
            , "Flow-1": list[10], "Flow-4": list[11], "Flow-7": list[12], "Flow-11": list[13]
                }
        list = pd.DataFrame(list, index=[index], columns=['date', "WaterID-1", "WaterID-2", "WaterID-3", "WaterID-4"
            , "WaterID-5", "WaterID-6", "WaterID-7"
            , "WaterID-8", "WaterID-11", "Flow-1","Flow-4", "Flow-7","Flow-11"])

        datalist = pd.concat([datalist,list])

    datalist.to_csv("../data/Water.csv", index=False)

def sliceCSV():
    input_file = "../data/Fix-Water.csv"
    output = "../data/TrainDataset.csv"

    # 读取源文件
    df = pd.read_csv(input_file)

    # 保存后1000行数据到新文件
    new_df = df.iloc[-43800:]
    new_df.to_csv(output, index=False)

def drew():
    import matplotlib.pyplot as plt
    import numpy as np

    # 创建数据
    x = np.linspace(0, 2 * np.pi, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)

    # 绘制曲线图
    plt.plot(x, y1, label='sin')
    plt.plot(x, y2, label='cos')

    # 添加图例
    plt.legend()

    # 显示图形
    plt.show()

if __name__=="__main__":
    path = "/Users/ljq/论文/数据/水文数据/md_wate_meas2023.csv"
    CSV_data(path)
    fix()
    sliceCSV()

